package com.sunck.common.shiro;

import com.sunck.common.config.Global;
import com.sunck.common.exception.ResultEnum;
import com.sunck.common.exception.ResultUtil;
import com.sunck.common.utils.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import com.alibaba.fastjson.JSON;

/**
 * 表单过滤类（验证码)
 *
 * @author LengChen
 * @version 1.0
 * @date 2020/8/18
 */
public class SunckFormAuthenticationFilter extends FormAuthenticationFilter {

    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        if (password==null){
            password = "";
        }
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);
        String captcha = getCaptcha(request);
        boolean mobile = isMobileLogin(request);
        return new UsernamePasswordToken(username,password.toCharArray(),rememberMe,host,captcha,mobile);
    }

    protected String getCaptcha(ServletRequest request) {
        return WebUtils.getCleanParam(request, Global.DEFAULT_Code_PARAM);
    }
    protected boolean isMobileLogin(ServletRequest request) {
        return WebUtils.isTrue(request, Global.DEFAULT_MOBILE_PARAM);
    }

    /**
     * 登录认证成功后回调方法
     * @param request
     * @param response
     * @throws Exception
     */
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                  ServletRequest request, ServletResponse response) throws Exception {
       //WebUtils.redirectToSavedRequest(request, response, JSON.toJSONString(ResultUtil.success()));
       // response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(JSON.toJSONString(ResultUtil.success()));
        return false;
    }

    /**
     * 登录失败后回调方法
     *
     */
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {
        String className = e.getClass().getName(), message = "";
        System.out.println(className);
        if (IncorrectCredentialsException.class.getName().equals(className) || AuthenticationException.class.getName().equals(className)
                || UnknownAccountException.class.getName().equals(className)){
            if(!"-1".equals(StringUtils.isNumeric(e.getMessage()))){
                message = e.getMessage();
            }else{
                message = ResultEnum.SHIRO_ERROR_4.getStringCode();
            }
        }
        else if (StringUtils.isNotBlank(e.getMessage())) {
            message = e.getMessage();
        }
        else{
            message = ResultEnum.UNKNOWN_ERROR.getStringCode();
            e.printStackTrace(); // 输出到控制台
        }
        request.setAttribute(getFailureKeyAttribute(), className);
        request.setAttribute(Global.DEFAULT_MESSAGE_PARAM, message);
        return true;
    }


}
